<script setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { updateArticleApi, getArticleApi } from "../../api/article";
const formData = ref({
  title: "",
  content: "",
  img: "",
});

const handleSelect = (e) => {
  const tempFilePaths = e.tempFilePaths;
  uni.uploadFile({
    fileType: "image",
    filePath: tempFilePaths[0],
    url: "http://localhost:3000/uploads/img",
    name: "file",
    success: ({ data }) => {
      formData.value.img = JSON.parse(data).path;
    },
    fail: (error) => {
      uni.showToast({
        title: "上传失败",
        icon: "fail",
        mask: true,
      });
    },
  });
};

const ids = ref("");
const submit = async () => {
  await updateArticleApi(ids.value, formData.value);
  uni.navigateBack();
};

const getArticle = async () => {
  const { title, img, content } = await getArticleApi(ids.value);

  formData.value = { title, img, content };
};

onLoad((options) => {
  ids.value = options.id;
  getArticle();
});
</script>

<template>
  <view class="add">
    <uni-forms :value="formData" labelWidth="80">
      <uni-forms-item name="title" label="文章标题">
        <uni-easyinput v-model="formData.title" placeholder="请输入文章标题" />
      </uni-forms-item>
      <uni-forms-item name="content" label="文章内容">
        <uni-easyinput
          type="textarea"
          v-model="formData.content"
          placeholder="请输入文章内容"
        />
      </uni-forms-item>

      <uni-forms-item name="img" label="上传文件">
        <uni-file-picker
          :limit="1"
          fileMediatype="image"
          @select="handleSelect"
        />
      </uni-forms-item>
    </uni-forms>
    <view class="add__btn-box">
      <button type="primary" @click="submit">编辑</button>
    </view>
  </view>
</template>
